<!--
 * @Author: windys
 * @Description: 
 * @Date: 2022-02-18 14:01:16
-->
<template>
  <van-uploader :after-read="afterRead" v-model="fileList"  />
</template>



<script >
import { defineComponent, ref } from "vue";
import { uploadimagetoken, imageupload } from "@/api/common";
import storage from "@/utils/storage";
export default defineComponent({
  setup(props,{emit}) {

    const user = ref(JSON.parse(storage.getStorage("v3_userinfo_mobile")));
    const fileList = ref([]);

    const uploader = ref(null);
    const afterRead = (file) => {
      console.log(file);
      var reader = new FileReader();
      reader.readAsDataURL(file.file);
      reader.onload = function (e) {};
      var userData = '{"Vod":{}}';
      uploader.value = createUploader();
      console.log(uploader, "upupu");
      uploader.value.addFile(file.file, null, null, null, userData);
      start();
    };
    const start = () => {
      if (uploader.value !== null) {
        uploader.value.startUpload();
      }
    };
    const createUploader = () => {
      // 此时可以自行将文件上传至服务器
      return new AliyunUpload.Vod({
        timeout: 60000,
        partSize: 1048576,
        parallel: 5,
        retryCount: 3,
        retryDuration: 2,
        region: "cn-shanghai",
        userId: "1303984639806000",
        // 添加文件成功
        addFileSuccess: function (uploadInfo) {},
        // 开始上传
        onUploadstarted: async (uploadInfo) => {
          //获取上传凭证
          const res = await uploadimagetoken({
            fileName: uploadInfo.file.name,
            userId: user.value.userId,
          });
          if (typeof res === "object") {
            uploader.value.setUploadAuthAndAddress(
              uploadInfo,
              res.uploadAuth,
              res.uploadAddress
            );
            const res2 = await imageupload({
              imageId: res.imageId,
              userId: user.value.userId,
            });

            if (typeof res2 === "object") {
              console.log(res2, "上传成功");
              fileList.value = [];
              fileList.value.push({ url: res2.url });
              emit("uploadSucc",res2.url)
            }
          }
        },
      });
    };
    return {
      fileList,
      afterRead,
    };
  },
});
</script>
